package com.gandong8.hbase.tool.config;

import com.gandong8.hbase.tool.config.properties.HbaseProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(HbaseProperties.class)
@Slf4j
public class HbaseConfig {

    @Autowired
    HbaseProperties hbaseProperties;

    @Bean
    public Connection createConnect(){
        try {
            return ConnectionFactory.createConnection(createConfig());
        } catch (Exception e) {
            log.error("hbase_create_connection_err", e);
            return null;
        }
    }

    private org.apache.hadoop.conf.Configuration createConfig() throws Exception {
        org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
        if (hbaseProperties == null) {
            throw new Exception("hbase_config_is_null");
        }
        conf.set("hbase.zookeeper.quorum", hbaseProperties.getZookeeperQuorum());
        conf.set("hbase.zookeeper.property.clientPort", hbaseProperties.getZookeeperPropertyClientPort());
        //客户端重试最大次数
        conf.set("hbase.client.retries.number", hbaseProperties.getClientRetriesNumber());
        //rpc超时时间,默认为60000ms
        conf.set("hbase.rpc.timeout", hbaseProperties.getRpcTimeout());
        //zookeeper的重试次数
        conf.set("zookeeper.recovery.retry", hbaseProperties.getZookeeperRecoveryRetry());
        //zookeeper重试的休眠时间，默认为1000ms
        conf.set("zookeeper.recovery.retry.intervalmill", hbaseProperties.getZookeeperRecoveryRetryIntervalmill());
        //一次操作的超时时间，有可能包含多个RPC请求，默认为1200000ms
        conf.set("hbase.client.operation.timeout", hbaseProperties.getClientOperationTimeout());
        //scan查询时每次与RegionServer交互的超时时间
        conf.set("hbase.client.scanner.timeout.period", hbaseProperties.getClientScannerTimeoutPeriod());
        return conf;
    }

}
